import axios from 'axios'
import { message } from 'ant-design-vue'

// 创建基础axios实例
const createRequest = (baseURL: string) => {
  const request = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 15000
    // 移除默认的Content-Type设置，让每个请求自己处理
  })

  // 请求拦截器
  request.interceptors.request.use(
    (config) => {
      // 从localStorage获取token
      const token = localStorage.getItem('token')
      if (token) {
        config.headers.Authorization = `${token}`
      }
      
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  // 响应拦截器
  request.interceptors.response.use(
    (response) => {
      return response.data
    },
    (error) => {
      console.error('API请求错误:', error)
      
      if (error.response) {
        const { status, data } = error.response
        
        switch (status) {
          case 401:
            message.error('登录已过期，请重新登录')
            // 清除本地存储的认证信息
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
            // 跳转到登录页
            window.location.href = '/'
            break
          case 403:
            message.error('没有权限访问该资源')
            break
          case 404:
            message.error('请求的资源不存在')
            break
          case 500:
            message.error('服务器内部错误')
            break
          default:
            message.error(data?.message || '请求失败')
        }
      } else if (error.request) {
        message.error('网络连接失败，请检查网络设置')
      } else {
        message.error('请求配置错误')
      }
      
      return Promise.reject(error)
    }
  )

  return request
}

// 创建不同服务的request实例
export const userRequest = createRequest('/api/user')
export const mediaRequest = createRequest('/api/media')
export const studyRequest = createRequest('/api/study')

export const mallRequest = createRequest('/api/mall')
export const cartRequest = createRequest('/api/cart')
export const aiRequest = createRequest('/api/ai')
export const searchRequest = createRequest('/api/search')


// 默认request实例（向后兼容）
const defaultRequest = createRequest('/api')

export default defaultRequest



